import 'dart:typed_data';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/ui/service_execute/service_execute_home_page.dart';
import 'package:ls_work/viewmodel/service_execute/new_service_execute_view_model.dart';

import '../../login/page/user_manager.dart';
import '../../res/resources.dart';
import '../../util/image_utils.dart';

class NewServiceExecutePage extends BaseStatefulMvvmWidget {
  final String? elderCode;
  final String? customerElderId;

  NewServiceExecutePage({this.elderCode, this.customerElderId});

  @override
  State<StatefulWidget> createState() => _NewServiceExecuteState();
}

class _NewServiceExecuteState
    extends BaseMvvmState<NewServiceExecuteViewModel, NewServiceExecutePage> {
  @override
  Widget buildLoadingContentView() {
    var customer = viewModel.customerInfo;
    return customer==null?Container(): Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ImageLoad(
                "${HttpApi.imageHead}${customer.headimageId}",
                fit: BoxFit.cover,
                placeholder: ImageUtils.getImgPath(
                    customer.sex == 0 ? "nan" : "nv"),
                errorImage: ImageUtils.getImgPath(
                    customer.sex == 0 ? "nan" : "nv"),width: 60,height: 60,).addToContainer(width: 60,height: 60).toCircle(),
            SizedBox(width: 16,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CommonText(customer.name),
                SizedBox(height: 16,),
                CommonText("${customer.bedNo} ${customer.nurseLevelName}",textSize: 14)
              ],
            ).setWeight(1),
            TextButton(onPressed: (){
              Go().push(ServiceExecuteHomePage(customerId: widget.customerElderId,scanCode: widget.elderCode,showOnlyFinish: true,title: "今日服务记录",));
            }, child: Text('今日服务记录',style: TextStyle(
              color: Colors.blue
            ),),style: ButtonStyle(
              shape: WidgetStateProperty.all(RoundedRectangleBorder(
                side: BorderSide(color: Colors.blue),
                borderRadius: 4.borderRadius
              ))
            ),)
          ],
        ).addToContainer(padding: EdgeInsets.symmetric(vertical: 12,horizontal: 16),color: Colors.white),
        Gaps.line,
        Row(
          children: [
            ListView.separated(
                    itemBuilder: (context, index) {
                      var type = viewModel.taskList[index];
                      return Stack(
                        alignment: Alignment.center,
                        children: [
                          Container(
                            width: double.infinity,
                            constraints: BoxConstraints(minHeight: 60),
                          ),
                          CommonText(
                            type.name,
                            textAlign: TextAlign.center,
                          ).setLocation(left: 10, right: 10),
                          Text(
                            type.count.toString(),
                            style: TextStyle(color: Colors.white, fontSize: 13),
                          )
                              .addToContainer(
                                  decoration: BoxDecoration(
                                      color: Colors.red,
                                      borderRadius: 20.borderRadius),
                                  alignment: Alignment.center,
                                  constraints: BoxConstraints(
                                      minWidth: 20, minHeight: 20))
                              .setLocation(right: 0, top: 0)
                        ],
                      ).onTap(() {
                        setState(() {
                          viewModel.selectIndex = index;
                        });
                      }).addToContainer(
                          width: double.infinity,
                          color: viewModel.selectIndex == index
                              ? Colors.white
                              : Colors.transparent,
                          constraints: BoxConstraints(minHeight: 60),
                          alignment: Alignment.center);
                    },
                    separatorBuilder: (context, index) {
                      return Container();
                    },
                    itemCount: viewModel.taskList.length)
                .addToContainer(
              width: 90,
            ),
            ListView(
              children: [
                if(viewModel.canBatchTask.isNotEmpty)
                  serviceItemContent(viewModel.canBatchTask).addToContainer(color: Colors.white),

                if(viewModel.singleTask.isNotEmpty)
                  ...[
                    SizedBox(height: 12,),

                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 16,),
                        CommonText('  以下项目需要填写数值，请单独点击操作',textColor: Colors.orange,textSize: 14),
                        serviceItemContent(viewModel.singleTask)
                      ],
                    ).addToContainer(color: Colors.white)
                  ]
              ],
            ).setWeight(1)
          ],
        ).setWeight(1),

        if(viewModel.selectItemList.isNotEmpty)
          Row(
            children: [
              SizedBox(width: 15,),
              TextButton(onPressed: (){
                viewModel.clearSelectBatch();
              },style: ButtonStyle(
                shape: WidgetStateProperty.all(RoundedRectangleBorder(side: BorderSide(color: Colors.grey[700]!),borderRadius: 4.borderRadius))
              ), child: Text("取消选择",style: TextStyle(color: Colors.black,fontSize: 16),)).setWeight(1),

              if(viewModel.selectItemList.length==1)
                ...[
                  SizedBox(width: 12,),
                  TextButton(onPressed: (){
                    viewModel.inputClick(viewModel.selectItemList.first);
                  },style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(Colors.blue)
                  ), child: Text("备注并完成",style: TextStyle(color: Colors.white,fontSize: 16),)).setWeight(1),

                ],
              SizedBox(width: 12,),
              TextButton(onPressed: (){
                viewModel.showApplyBatchDialog();
              },style: ButtonStyle(
                  backgroundColor: WidgetStateProperty.all(Colors.blue)
              ), child: Text("完成任务",style: TextStyle(color: Colors.white,fontSize: 16),)).setWeight(1),
              SizedBox(width: 15,),
            ],
          ).addToContainer(padding: EdgeInsets.only(bottom: 16,top: 12),color: Colors.white)
      ],
    );
  }

  Widget serviceItemContent(List<ServiceItem> list){
    return GridView.count(
      crossAxisCount: 3,
      crossAxisSpacing: 10,
      mainAxisSpacing: 10,
      childAspectRatio: 0.78,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      children:
      list.map((e) {
        return Stack(
          children: [
            Column(
              children: [
                Stack(
                  alignment: Alignment.center,
                  children: [
                    e.image!=null?
                    AspectRatio(aspectRatio: 1,child: CachedNetworkImage(
                      imageUrl:
                      "${HttpApi.imageHead}${e.image}",
                      fit: BoxFit.cover,
                      httpHeaders: {"Cookie":UserManager.cookieStr},
                      width: double.infinity,
                      height: double.infinity,
                    ),).toRound(borderRadius: 6.borderRadius
                    ):AspectRatio(aspectRatio: 1,child: Text(e.itemName??"",textAlign: TextAlign.center,).addToContainer(
                        width: double.infinity,
                        height: double.infinity,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey),
                            borderRadius: 6.borderRadius
                        )
                    ),),
                    
                    if(viewModel.selectItemList.contains(e))
                    ...[
                      Container(color: Colors.black.withOpacity(0.4),),
                      Icon(Icons.check,color: Colors.white,).addToContainer(
                        decoration: BoxDecoration(
                          color: Colors.green,
                          shape: BoxShape.circle
                        ),
                        width: 35,
                        height: 35,
                        alignment: Alignment.center
                      )
                    ]
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                CommonText(e.itemName, textSize: 14)
              ],
            ).setLocation(left: 0, right: 0),
            Text(
              (e.taskList??[]).length.toString(),
              style: TextStyle(color: Colors.white, fontSize: 13),
            )
                .addToContainer(
                decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: 20.borderRadius),
                alignment: Alignment.center,
                constraints:
                BoxConstraints(minWidth: 20, minHeight: 20))
                .setLocation(right: 0)
          ],
        ).onTap(() {
          if(e.canBatch){
            setState(() {
              if(viewModel.selectItemList.contains(e)){
                viewModel.selectItemList.remove(e);
              }else{
                viewModel.selectItemList.add(e);
              }
            });
          }else{
            if(viewModel.selectItemList.isEmpty){
              //todo:直接弹窗
              viewModel.inputClick(e);
            }else{
              //todo:清空提示
              viewModel.showClearApplyDialog(e);
            }
          }
        });
      }).toList(),
    );
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      backgroundColor: Colours.bg_color,
      appBar: AppBar(
        title: Text("服务执行"),
      ),
      body: loadingContentWidget,
    );
  }

  @override
  NewServiceExecuteViewModel createViewModel() {
    return NewServiceExecuteViewModel(context,
        elderCode: widget.elderCode, customerElderId: widget.customerElderId);
  }

  @override
  void onRetryClick() {
    viewModel.requestRefresh(showAni: false);
  }
}
